﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ServiceModel;
using WCFServiceWebRole1.Services;
using GlobalObjects;
using System.ServiceModel.Web;
using System.ServiceModel.Description;
using WCFServiceWebRole1.DataObjects;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;


namespace IotWebService_Intergration_Test
{
    [TestClass]
    public class DeviceServiceTests
    {
        #region class Variables

        static readonly string UserServiceBaseAddress = "http://localhost:8000/Services/users.svc";
        static readonly string DeviceServiceBaseAddress = "http://localhost:8080/Services/device.svc";


        static ServiceHost userHost;
        static ServiceHost deviceHost;

        Iusers userProxy;
        Idevice deviceProxy;

        static User testUser;
        static User invalidUser;
        Sensor testSensor;

        Sensor secondSensor;

        static Device testDevice = new Device();
        static Device secondDevice;
        static int testUserid;
        static int invalidUserid;
        static int testSensorid;
        static int secondSensorid;

        #endregion

        [ClassInitialize]
        public static void ClassInitialize(TestContext context)
        { 
            testUser = new User()
        {
            Country = "India",
            Email = "integrationtest@gmail.com",
            FirstName = "Integration",
            LastName = "Test",
            Organisation = "Microsoft",
            Password = "testing",
            Purpose = "WCFRestTest",      
            Title = "Mr.",
            Username = "deviceusertesting"

        };
        invalidUser = new User()
        {
            Country = "India",
            Email = "integrationtest@gmail.com",
            FirstName = "Integration",
            LastName = "Test",
            Organisation = "Microsoft",
            Password = "testing",
            Purpose = "WCFRestTest",
            Title = "Mr.",
            Username = "deviceusertesting2"
        };
            userHost = new ServiceHost(typeof(user));
            userHost.AddDefaultEndpoints();
            userHost.Open();

            deviceHost = new ServiceHost(typeof(device));
            deviceHost.AddDefaultEndpoints();
            deviceHost.Open();

        }

        [ClassCleanup]
        public static void ClassCleanup()
        {
            userHost.Close();
            deviceHost.Close();
        }

        [TestInitialize]
        public void Initialize()
        {
            WebChannelFactory<Iusers> factory = new WebChannelFactory<Iusers>(new Uri(UserServiceBaseAddress));
            factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
            userProxy = factory.CreateChannel();

            WebChannelFactory<Idevice> devicefactory = new WebChannelFactory<Idevice>(new Uri(DeviceServiceBaseAddress));
            devicefactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
            deviceProxy = devicefactory.CreateChannel();
        }

        [TestCleanup]
        public void Cleanup()
        {
            //     ((IClientChannel)this.userProxy).Close();
        }

        #region User Creation and Deletion

        //testing addUser Method
        [TestMethod]
        public void device_addNewUser_valid()
        {
            UserDetailsResponse createdUser = userProxy.addUser(testUser);
            testUserid = createdUser.response.Id;

            UserDetailsResponse createdUser1 = userProxy.addUser(invalidUser);
            invalidUserid = createdUser1.response.Id;

            Assert.AreEqual(userProxy.getUserByUserId(createdUser.response.Id.ToString()).response.Username, testUser.Username);
            Assert.AreEqual(userProxy.getUserByUserId(createdUser1.response.Id.ToString()).response.Username, invalidUser.Username);

            Debug.WriteLine(testUserid);

        }

        //testing deleteUser Method 
        [TestMethod]
        public void device_deleteUser_valid()
        {

            Debug.WriteLine("testUser"+testUserid+".TestUsername:"+testUser.Username);
            Debug.WriteLine("InvalidUser" + invalidUserid + ".InvalidUsername:" + invalidUser.Username);


            UserDeleteContract deleteUser = new UserDeleteContract()
            {
                Id = testUserid,
                Password = testUser.Password,
            };
            Assert.IsTrue(userProxy.deleteUser(testUserid.ToString(), deleteUser));

            UserDeleteContract deleteUser2 = new UserDeleteContract()
            {
                Id = invalidUserid,
                Password = invalidUser.Password,
            };
            Assert.IsTrue(userProxy.deleteUser(invalidUserid.ToString(), deleteUser2));

        }

        #endregion

        #region addDevice

        //testing addDevice Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void addDevice_inValid_emptyFields()
        {
            Device newDevice = new Device()
            {
                Name = "",
                Description = "Test Device",
                User_id = testUserid,
                Location = "London",
                Longlat = "51.542758680507625, 0.052399635314941406",
                Privacy = "public"
            };

            DeviceDetailsResponse addedDevice = userProxy.addDevice(newDevice);
            testDevice = addedDevice.response;
            Assert.IsNull(addedDevice);
        }

        //testing addDevice Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void addDevice_inValid_nullFields()
        {
            Device newDevice = new Device()
            {
                Name = "TestDevice",
                Description = "Test Device",
                User_id = testUserid,
                Location = null,
                Longlat = "51.542758680507625, 0.052399635314941406",
                Privacy = "private"
            };

            DeviceDetailsResponse addedDevice = userProxy.addDevice(newDevice);
            testDevice = addedDevice.response;
            Assert.IsNull(addedDevice);
        }

        //testing addDevice Method - Path 3
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void addDevice_inValid_notValidPrivacy()
        {
            Device newDevice = new Device()
            {
                Name = "TestDevice",
                Description = "Integration testing Device",
                Location = "London, Uk",
                Longlat = "51.542758680507625, 0.052399635314941406",
                User_id = testUserid,
                Privacy = "Private"
            };

            DeviceDetailsResponse addedDevice = userProxy.addDevice(newDevice);
            testDevice = addedDevice.response;
            Assert.IsNull(addedDevice);
        }

        //testing addDevice Method - Path 4
        [TestMethod]
        public void addDevice_Valid()
        {
            Device newDevice = new Device()
            {
                Name = "TestDevice",
                User_id = testUserid,
                Description = "Integration testing Device",
                Location = "London, UK",
                Longlat = "51.524485462825666, -0.13473272323608398",
                Privacy = "public"
            };

            Device privateDevice = new Device()
            {
                Name = "PrivateDevice",
                User_id = invalidUserid,
                Description = "Integration testing Device",
                Location = "London, UK",
                Longlat = "51.542758680507625, 0.052399635314941406",
                Privacy = "private"
            };

            DeviceDetailsResponse addedDevice = userProxy.addDevice(newDevice);
            DeviceDetailsResponse secondAddedDevice = userProxy.addDevice(privateDevice);
            testDevice = addedDevice.response;
            secondDevice = secondAddedDevice.response;
            Assert.AreEqual(newDevice.Name, addedDevice.response.Name);
            Debug.WriteLine("testDeviceid:"+testDevice.Id);
            Debug.WriteLine("secondDeviceid:" + secondDevice.Id);

        }

        //testing addDevice Method - Path 5
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void addDevice_inValid_deviceNameAlreadyExist()
        {
            Device newDevice = new Device()
            {
                Name = "TestDevice",
                User_id = testUserid,
                Description = "Integration testing Device",
                Location = "London, UK",
                Longlat = "51.542758680507625, 0.052399635314941406",
                Privacy = "private"
            };
            DeviceDetailsResponse addedDevice = userProxy.addDevice(newDevice);
            testDevice = addedDevice.response;
            Assert.IsNull(addedDevice);
        }

        #endregion

        #region getDevicesList

        //testing getDevicesList Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getDevicesList_inValid_userIdNAN()
        {
            Assert.IsNull(userProxy.getDevicesList("hello", "private"));
        }

        //testing getDevicesList Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getDevicesList_inValid_notValidPrivacy()
        {
            Assert.IsNull(userProxy.getDevicesList(testUserid.ToString(), "Private"));
        }

        //testing getDevicesList Method - Path 3
        [TestMethod]
        [ExpectedException(typeof(WebException), "Raise exception when service returns exception")]
        public void getDevicesList_inValid_userIdDoesNotExist()
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/devices/list?userid=9455&privacy=private");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "GET";
            
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
         

          //  Assert.IsNull(userProxy.getDevicesList("9455", "private"));
        }

        //testing getDevicesList Method - Path 4
        [TestMethod]
        [ExpectedException(typeof(WebException), "Raise exception when service returns exception")]
        public void getDevicesList_inValid_NoDevice()
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/devices/list?userid=" + invalidUser.Id.ToString() + "&privacy=" + "private");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "POST";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                Debug.WriteLine(result);
            }



           // Assert.IsNull(userProxy.getDevicesList(invalidUserid.ToString(), "private"));
        }

        //testing getDevicesList Method - Path 5
        [TestMethod]
        public void getDevicesList_Valid_allDevices()
        {
            bool found = false;
            int foundDeviceId = 0;
            List<DeviceDetailsResponse> response = userProxy.getDevicesList(testUserid.ToString(), "all");
            foreach (var item in response)
            {
                if (item.response.Id == testDevice.Id)
                {
                    found = true;
                    foundDeviceId = item.response.Id;
                }
            }
            if (found)
            {
                Assert.AreEqual(foundDeviceId, testDevice.Id);
            }
            else
            {
                Assert.Fail();
            }

            bool found1 = false;
            int foundDeviceId1 = 0;
            List<DeviceDetailsResponse> response1 = userProxy.getDevicesList(invalidUserid.ToString(), "all");
            foreach (var item in response)
            {
                if (item.response.Id == secondDevice.Id)
                {
                    found1 = true;
                    foundDeviceId1 = item.response.Id;
                }
            }
            if (found1)
            {
                Assert.AreEqual(foundDeviceId, secondDevice.Id);
            }
            else
            {
                Assert.Fail();
            }
        }

        //testing getDevicesList Method - Path 6
        [TestMethod]
        public void getDevicesList_Valid_publicDevices()
        {
            bool found = false;
            int foundDeviceId = 0;
            List<DeviceDetailsResponse> response = userProxy.getDevicesList(testUserid.ToString(), "public");
            foreach (var item in response)
            {
                if (item.response.Id == testDevice.Id)
                {
                    found = true;
                    foundDeviceId = item.response.Id;
                }
            }
            if (found)
            {
                Assert.AreEqual(foundDeviceId, testDevice.Id);
            }
            else
            {
                Assert.Fail();
            }
        }

        //testing getDevicesList Method - Path 7
        [TestMethod]
        public void getDevicesList_Valid_privateDevices()
        {
            bool found = false;
            String foundDeviceName = "";
            List<DeviceDetailsResponse> response = userProxy.getDevicesList(invalidUserid.ToString(), "private");
            foreach (var item in response)
            {
                if (item.response.Name == "PrivateDevice")
                {
                    found = true;
                    foundDeviceName = item.response.Name;
                }
            }
            if (found)
            {
                Assert.AreEqual(foundDeviceName, "PrivateDevice");
            }
            else
            {
                Assert.Fail();
            }
        }


        #endregion

        //prob
        #region getDevice

        //testing getDevice Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(WebException), "Raise exception when service returns exception")]
        public void getDevice_inValid_userIdDoesNotExist()
        {

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/devices?userid=9425&deviceid="+testDevice.Id.ToString());
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "GET";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
         


        //    Assert.IsNull(userProxy.getDevice(9425, testDevice.Id));
        }

        //prob
        //testing getDevice Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getDevice_inValid_deviceIdDoesNotExist()
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/devices?userid="+testUserid+"&deviceid=9225");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "GET";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
         
            //Assert.IsNull(userProxy.getDevice(testUserid, 9225));
        }

        //testing getDevice Method - Path 3
        [TestMethod]
        public void getDevice_valid_userNotOwnerOfPublicDevice()
        {
            Assert.AreEqual(testDevice.Id, userProxy.getDevice(invalidUserid, testDevice.Id).response.Id);
        }

        //testing getDevice Method - Path 4
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getDevice_inValid_userNotOwnerOfPrivateDevice()
        {
            Assert.IsNull(userProxy.getDevice(testUserid, secondDevice.Id));
        }

        //testing getDevice Method - Path 5
        [TestMethod]
        public void getDevice_valid()
        {
            Assert.AreEqual(testDevice.Id, userProxy.getDevice(testUserid, testDevice.Id).response.Id);
        }


        #endregion

        #region checkDeviceName

        //testing checkDeviceName Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void checkDeviceName_inValid_userIdDoesNotExist()
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/devices/checkdevicename?userid=9651&devicename=TestDevice");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "GET";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
         
         //   Assert.IsNull(userProxy.checkDeviceName(9651, "TestDevice"));
        }

        //testing checkDeviceName Method - Path 2
        [TestMethod]
        public void checkDeviceName_inValid_deviceNameAlreadyExists()
        {
            Assert.IsTrue(userProxy.checkDeviceName(testUserid, testDevice.Name));
        }


        //testing checkDeviceName Method - Path 3
        [TestMethod]
        public void checkDeviceName_Valid()
        {
            Assert.IsFalse(userProxy.checkDeviceName(testUserid, "TestDevice2"));
        }


        #endregion

        #region updateDevice

        //testing updateDevice Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void updateDevice_inValid_userIdNAN()
        {
            Device updateDevice = new Device()
            {
                Name = testDevice.Name,
                User_id = testDevice.User_id,
                Description = testDevice.Description,
                Location = testDevice.Location,
                Longlat = testDevice.Longlat,
                Privacy = testDevice.Privacy,
                Id = testDevice.Id
            };
            Assert.IsNull(userProxy.updateDevice("hello", updateDevice));
        }

        //testing updateDevice Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void updateDevice_inValid_deviceIdNotMatch()
        {
            Device updateDevice = new Device()
            {
                Name = testDevice.Name,
                User_id = testDevice.User_id,
                Description = testDevice.Description,
                Location = testDevice.Location,
                Longlat = testDevice.Longlat,
                Privacy = testDevice.Privacy,
                Id = 345678

            };
            Assert.IsNull(userProxy.updateDevice("34567", updateDevice));
        }

        //testing updateDevice Method - Path 3
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void updateDevice_inValid_deviceIdDoesNotExist()
        {
            Device updateDevice = new Device()
            {
                Name = testDevice.Name,
                User_id = testDevice.User_id,
                Description = testDevice.Description,
                Location = testDevice.Location,
                Longlat = testDevice.Longlat,
                Privacy = testDevice.Privacy,
                Id = 345678

            };
            Assert.IsNull(userProxy.updateDevice("345678", updateDevice));
        }

        //testing updateDevice Method - Path 4
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void updateDevice_inValid_deviceIdEmpty()
        {
            Device updateDevice = new Device()
            {
                Name = testDevice.Name,
                User_id = testDevice.User_id,
                Description = testDevice.Description,
                Location = testDevice.Location,
                Longlat = testDevice.Longlat,
                Privacy = testDevice.Privacy,
            };
            Assert.IsNull(userProxy.updateDevice(testDevice.Id.ToString(), updateDevice));
        }


        //testing updateDevice Method - Path 5
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void updateDevice_inValid_deviceNameAlreadyExist()
        {
            Device updateDevice = new Device()
            {
                Name = "PrivateDevice",
                User_id = testDevice.User_id,
                Description = testDevice.Description,
                Location = testDevice.Location,
                Longlat = testDevice.Longlat,
                Privacy = testDevice.Privacy,
            };
            Assert.IsNull(userProxy.updateDevice(testDevice.Id.ToString(), updateDevice));
        }

        //testing updateDevice Method - Path 6
        [TestMethod]
        public void updateDevice_inValid_EmptyField()
        {
            Device updateDevice = new Device()
            {
                Name = testDevice.Name,
                User_id = testDevice.User_id,
                Description = testDevice.Description,
                Location = testDevice.Location,
                Longlat = "",
                Privacy = testDevice.Privacy,
                Id = testDevice.Id

            };
            Assert.AreEqual(testDevice.Longlat, userProxy.updateDevice(testDevice.Id.ToString(), updateDevice).response.Longlat);
        }

        //testing updateDevice Method - Path 7
        [TestMethod]
        public void updateDevice_inValid_NullField()
        {
            Device updateDevice = new Device()
            {
                Name = testDevice.Name,
                User_id = testDevice.User_id,
                Description = testDevice.Description,
                Location = null,
                Longlat = testDevice.Longlat,
                Privacy = testDevice.Privacy,
                Id = testDevice.Id

            };
            Assert.AreEqual(testDevice.Location, userProxy.updateDevice(testDevice.Id.ToString(), updateDevice).response.Location);
        }

        //testing updateDevice Method - Path 8
        [TestMethod]
        public void updateDevice_valid()
        {
            Device updateDevice = new Device()
            {
                Name = testDevice.Name,
                User_id = testDevice.User_id,
                Description = testDevice.Description,
                Location = "Chennai,IN",
                Longlat = testDevice.Longlat,
                Privacy = testDevice.Privacy,
                Id = testDevice.Id

            };
            Assert.AreEqual("Chennai,IN", userProxy.updateDevice(testDevice.Id.ToString(), updateDevice).response.Location);
        }

        #endregion

        #region changeRepository

        //testing changeRepository Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void changeRepository_inValid_deviceIdNAN()
        {
            CustomRepo repoInfo = new CustomRepo()
            {
                Url = "uclmongovm.cloudapp.net",
                Port = 27017,
                DBName = "test",
                Id = testDevice.Id

            };
            Assert.IsNull(userProxy.changeRepository("hello", repoInfo));
        }

        //testing changeRepository Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(WebException), "Raise exception when service returns exception")]
        public void changeRepository_inValid_emptyField()
        {
            CustomRepo repoInfo = new CustomRepo()
            {
                Url = "uclmongovm.cloudapp.net",
                DBName = "test",
                Id = testDevice.Id

            };
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/customrepo/device/" + testDevice.Id.ToString());
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "POST";

            JavaScriptSerializer js2 = new JavaScriptSerializer();
            string json = js2.Serialize(repoInfo);


            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
   
         //   Assert.IsNull(userProxy.changeRepository(testDevice.Id.ToString(), repoInfo));
        }

        //testing changeRepository Method - Path 3
        [TestMethod]
        [ExpectedException(typeof(WebException), "Raise exception when service returns exception")]
        public void changeRepository_inValid_nullField()
        {
            CustomRepo repoInfo = new CustomRepo()
            {
                Url = "uclmongovm.cloudapp.net",
                Port = 27017,
                DBName = null,
                Id = testDevice.Id
            };

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/customrepo/device/" + testDevice.Id.ToString());
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "POST";

            JavaScriptSerializer js2 = new JavaScriptSerializer();
            string json = js2.Serialize(repoInfo);


            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
   
           // Assert.IsNull(userProxy.changeRepository(testDevice.Id.ToString(), repoInfo));
        }

        //testing changeRepository Method - Path 4
        [TestMethod]
        [ExpectedException(typeof(WebException), "Raise exception when service returns exception")]
        public void changeRepository_inValid_deviceIdDoesNotMatch()
        {

            CustomRepo repoInfo = new CustomRepo()
            {
                Url = "uclmongovm.cloudapp.net",
                Port = 27017,
                DBName = "test",
                Id = 9155
            };

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/customrepo/device/" + testDevice.Id.ToString());
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "POST";

            JavaScriptSerializer js2 = new JavaScriptSerializer();
            string json = js2.Serialize(repoInfo);


            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
   


          //  Assert.IsNull(userProxy.changeRepository(testDevice.Id.ToString(), repoInfo));
        }

        //testing changeRepository Method - Path 5
        [TestMethod]
        [ExpectedException(typeof(WebException), "Raise exception when service returns exception")]
        public void changeRepository_inValid_deviceIdDoesNotExist()
        {
            CustomRepo repoInfo = new CustomRepo()
            {
                Url = "uclmongovm.cloudapp.net",
                Port = 27017,
                DBName = "test",
                Id = 9155
            };

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/customrepo/device/9155");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "POST";

            JavaScriptSerializer js2 = new JavaScriptSerializer();
            string json = js2.Serialize(repoInfo);


            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
   
           // Assert.IsNull(userProxy.changeRepository("9155", repoInfo));
        }

        //testing changeRepository Method - Path 6
        [TestMethod]
        public void changeRepository_valid()
        {
            CustomRepo repoInfo = new CustomRepo()
            {
                Url = "iot:gadg3t33r@ds031108.mongolab.com",
                Port = 31108,
                DBName = "iot",
                Id = testDevice.Id

            };
            Assert.AreEqual("mongodb://iot:gadg3t33r@ds031108.mongolab.com:31108/iot", userProxy.changeRepository(testDevice.Id.ToString(), repoInfo));
        }

        #endregion 

        #region getRepository

        //testing getRepository Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getRepository_inValid_deviceIdNAN()
        {
            Assert.IsNull(userProxy.getRepository("hello"));
        }

        //testing getRepository Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getRepository_inValid_deviceIdDoesNotExist()
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000/Services/users.svc/customrepo/device/9155");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "GET";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

         //   Assert.IsNull(userProxy.getRepository("9155"));
        }

        //testing getRepository Method - Path 3
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getRepository_valid()
        {
            Assert.AreEqual("iot:gadg3t33r@ds031108.mongolab.com", userProxy.getRepository(testDevice.Id.ToString()).Url);
        }

        #endregion Deveice Registration

        //testing addSensor Method - Path 1
        [TestMethod]
        public void addSensor_valid()
        {
            //   List<SensorRegistrationRequest> sensors = new List<SensorRegistrationRequest>;
            //  sensors.Add(new SensorRegistrationRequest(){Type="Test",Name="TestSensor",Metadata="Coming Soon",Make="GHI",Interval_send="12",Interval_measure="34"});

            // DeviceRegistrationRequestDataContract request = new DeviceRegistrationRequestDataContract();
            //request.DeviceId=testDevice.Id;
            //request.Sensors=sensors;
            Debug.WriteLine("testDeviceId:" + testDevice.Id);
            Debug.WriteLine("secondDeviceid:" + secondDevice.Id);



            testSensor = new Sensor() { Deviceid = testDevice.Id, Type = "Test", Name = "TestSensor", Metadata = "Coming Soon", Make = "GHI", Interval_send = "12", Interval_measure = "34" };
            secondSensor = new Sensor() { Deviceid = secondDevice.Id, Type = "Test", Name = "TestSensor2", Metadata = "Coming Soon", Make = "GHI", Interval_send = "12", Interval_measure = "34" };



            testSensorid = Convert.ToInt32(userProxy.addSensor(testSensor));
            secondSensorid = Convert.ToInt32(userProxy.addSensor(secondSensor));

            Debug.WriteLine("testSensorid:" + testSensorid);
            Debug.WriteLine("secondSensorid:" + secondSensorid);
        }

        #region getSensorsList

        //testing getSensorsList Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getSensorsList_inValid_DeviceIdDoesNotExist()
        {
            Assert.IsNull(userProxy.getSensorsList(23940));
        }

        //testing getSensorsList Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getSensorsList_inValid_DeviceIdExistNoSensor()
        {
            Assert.IsNull(userProxy.getSensorsList(testDevice.Id));
        }

        //testing getSensorsList Method - Path 3
        [TestMethod]
        public void getSensorsList_valid()
        {
            Assert.AreEqual(1, userProxy.getSensorsList(testDevice.Id).Count);
        }

        #endregion

        #region getSensorsById

        //testing getSensorsById Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getSensorsById_inValid_sensorIdNAN()
        {
            Assert.IsNull(userProxy.getSensorsById("hello"));
        }

        //testing getSensorsById Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getSensorsById_inValid_sensorIdDoesNotExist()
        {
            Assert.IsNull(userProxy.getSensorsList(23940));
        }

        //testing getSensorsById Method - Path 3
        [TestMethod]
        public void getSensorsById_valid()
        {
            Assert.AreEqual(testSensor.Name, userProxy.getSensorsById(testSensorid.ToString()).SensorDetails.Name);
        }

        #endregion

        #region getNearestSensors

        //testing getNearestSensors Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getNearestSensors_inValid_sensorIdDoesNotExist()
        {
            Assert.IsNull(userProxy.getNearestSensors(testUserid,23445,40));
        }

        //testing getNearestSensors Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void getNearestSensors_inValid_userIdDoesNotExist()
        {
            Assert.IsNull(userProxy.getNearestSensors(23445, 23445, 40));
        }

        //testing getNearestSensors Method - Path 3
        [TestMethod]
        public void getNearestSensors_inValid_noNearestSensors()
        {
            Assert.IsNull(userProxy.getNearestSensors(testUserid, testSensorid, 1));
        }

        //testing getNearestSensors Method - Path 4
        [TestMethod]
        public void getNearestSensors_valid()
        {
             bool found = false;
            string foundSensorName = "";
            List<NearestSensorsResponse> response = userProxy.getNearestSensors(testUserid,testSensorid,20);
            foreach (var item in response)
            {
                if (item.Name==secondSensor.Name)
                {
                    found = true;
                    foundSensorName = item.Name;
                }
            }
            if (found)
            {
                Assert.AreEqual(foundSensorName, secondSensor.Name);
            }
            else
            {
                Assert.Fail();
            }

        }

        #endregion

        #region sharePrivateDevice

        //testing sharePrivateDevice Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void sharePrivateDevice_inValid_deviceIdNAN()
        {
            ShareDeviceContract sharer = new ShareDeviceContract(){OwnerId=testUserid,SharerUsername="ayyappan"};
            Assert.IsNull(userProxy.sharePrivateDevice("hello",sharer));
        }

        //testing sharePrivateDevice Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void sharePrivateDevice_inValid_deviceIdDoesNotExist()
        {
            ShareDeviceContract sharer = new ShareDeviceContract() { OwnerId = testUserid, SharerUsername = "ayyappan" };
            Assert.IsNull(userProxy.sharePrivateDevice("23455", sharer));
        }

        //testing sharePrivateDevice Method - Path 3
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void sharePrivateDevice_inValid_sharerUserNameDoesNotExist()
        {
            ShareDeviceContract sharer = new ShareDeviceContract() { OwnerId = testUserid, SharerUsername = "FuckYou" };
            Assert.IsNull(userProxy.sharePrivateDevice(secondDevice.Id.ToString(), sharer));
        }

        //testing sharePrivateDevice Method - Path 4
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void sharePrivateDevice_inValid_userNotOwnerOfDevice()
        {
            ShareDeviceContract sharer = new ShareDeviceContract() { OwnerId = 1092, SharerUsername = "ayyappan" };
            Assert.IsNull(userProxy.sharePrivateDevice(secondDevice.Id.ToString(), sharer));
        }

        //testing sharePrivateDevice Method - Path 5
        [TestMethod]
        public void sharePrivateDevice_valid()
        {
            ShareDeviceContract sharer = new ShareDeviceContract() { OwnerId = testUserid , SharerUsername = "ayyappan" };
            Assert.IsTrue(userProxy.sharePrivateDevice(secondDevice.Id.ToString(), sharer));
        }
        #endregion

        #region removeSharedPrivateDevice

        //testing removeSharedPrivateDevice Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void removeSharedPrivateDevice_inValid_deviceIdNAN()
        {
            ShareDeviceContract sharer = new ShareDeviceContract() { OwnerId = testUserid, SharerUsername = "ayyappan" };
            Assert.IsNull(userProxy.removeSharedPrivateDevice("hello", sharer));
        }

        //testing removeSharedPrivateDevice Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void removeSharedPrivateDevice_inValid_deviceIdDoesNotExist()
        {
            ShareDeviceContract sharer = new ShareDeviceContract() { OwnerId = testUserid, SharerUsername = "ayyappan" };
            Assert.IsNull(userProxy.removeSharedPrivateDevice("23435", sharer));
        }

        //testing removeSharedPrivateDevice Method - Path 3
        [TestMethod]
        public void removeSharedPrivateDevice_valid()
        {
            ShareDeviceContract sharer = new ShareDeviceContract() { OwnerId = testUserid, SharerUsername = "ayyappan" };
            Assert.IsTrue(userProxy.removeSharedPrivateDevice(secondDevice.Id.ToString(), sharer));
        }


        #endregion

        #region deleteDevice

        //testing deleteDevice Method - Path 1
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void deleteDevice_inValid_deviceIdNAN()
        {
            Assert.IsFalse(userProxy.deleteDevice("hello"));
        }

        //testing deleteDevice Method - Path 2
        [TestMethod]
        [ExpectedException(typeof(ProtocolException), "Raise exception when service returns exception")]
        public void deleteDevice_inValid_deviceIdNotExist()
        {
            Assert.IsFalse(userProxy.deleteDevice("2352355"));
        }

        //testing deleteDevice Method - Path 3
        [TestMethod]
        public void deleteDevice_Valid()
        {
            Assert.IsTrue(userProxy.deleteDevice(testDevice.Id.ToString()));
            Assert.IsTrue(userProxy.deleteDevice(secondDevice.Id.ToString()));


            //         Assert.IsTrue(userProxy.deleteDevice("2068"));
            //Assert.IsTrue(userProxy.deleteDevice("2069"));

        }

        #endregion


    }
}
